package com.xudm.cdg.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xudm.cdg.entity.config.TyqwConfig;
import com.xudm.cdg.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class TyqwApi {
    private final TyqwConfig tyqwConfig;
    private final HttpClientUtil clientUtil;

    public TyqwApi(TyqwConfig tyqwConfig, HttpClientUtil clientUtil) {
        this.tyqwConfig = tyqwConfig;
        this.clientUtil = clientUtil;
    }

    public JSONObject chatByQw(String question, String prompt) {
        // 通过 HttpClient 工具类发送请求获取聊天结果
        String chatUrl = tyqwConfig.getChatUrl();
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer " + tyqwConfig.getSecretKey());
        JSONObject body = new JSONObject();
        JSONArray messages = new JSONArray();

        JSONObject input = new JSONObject();
        JSONObject parameter = new JSONObject();

        if (StrUtil.isBlank(question)) {
            log.error("聊天问题不能为空");
            return null;
        }
        if (StrUtil.length(question) > 20000) {
            log.error("聊天问题长度超过20000个字符");
            return null;
        }
        JSONObject sysMessage = new JSONObject();
        sysMessage.put("role", "system");
        sysMessage.put("content", prompt);

        messages.add(sysMessage);

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", question);
        messages.add(userMessage);
        input.put("messages", messages);
        body.put("input", input);
        body.put("model", "qwen-turbo");
        parameter.put("result_format", "message");
        parameter.put("temperature", 0.3);
        body.put("parameters", parameter);

        String responseStr = clientUtil.sendPostRequest(chatUrl, body.toJSONString(), headers);
        return JSONObject.parseObject(responseStr);
    }
}
